//
//  WD_MyAVPlayer.m
//  BUDING
//
//  Created by HanWoonYong on 16/4/13.
//  Copyright © 2016年 HanWoonYong. All rights reserved.
//

#import "WD_MyAVPlayer.h"

@interface WD_MyAVPlayer()
@property (nonatomic, strong)WD_MyPlayerMaskView *maskView;
@end
@implementation WD_MyAVPlayer
+ (instancetype)shareAVPlayer {
    static WD_MyAVPlayer *player = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        player = [[self alloc] init];
    });
    return player;
}

- (void)initWithPlayLayerFrame:(CGRect)playLayerFrame MaskView:(WD_MyPlayerMaskView *)maskView {
    //    播放页面
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self];
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    self.playerLayer.bounds = self.playerFrame;
    self.playerLayer.backgroundColor = [[UIColor blackColor] CGColor];
}

- (void)setUrl:(NSString *)url {
    if (self.currentItem) {
        // 移除上次监听时间
        [self removeObserver:self forKeyPath:@"status"];
        
    }
    
    //    if (self.currentItem) {
    //            [self.playItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
    //    }
    //    [self.playItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
    self.playItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:url]];
    [self addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];// 监听status属性
    
    [self replaceCurrentItemWithPlayerItem:self.playItem];
    
    [self play];
}

#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if (object == self) {
        if ([keyPath isEqualToString:@"status"]) {
            if (self.status == AVPlayerStatusReadyToPlay) {
                //                self.playState = WDPlayerStatePlaying;
            } else if (self.playItem.status == AVPlayerStatusFailed) {
                //          [self.maskView.activity startAnimating];
            }
        }
    }
}

- (NSTimeInterval)availableTime {
    NSArray *loadTimeRange = [[self currentItem] loadedTimeRanges];
    CMTimeRange timeRange = [loadTimeRange.firstObject CMTimeRangeValue];// 获取缓冲区域
    float startSecond = CMTimeGetSeconds(timeRange.start);
    float durationSecond = CMTimeGetSeconds(timeRange.duration);
    NSTimeInterval result = startSecond + durationSecond;// 计算缓冲总进度
    return result;
}




@end
